<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive, onMounted } from 'vue'
import { ElTree, ElInput, ElDivider, ElTag, ElUpload, ElIcon, ElMessage } from 'element-plus'
import { selectionType } from '@/api/login/types'

import {
  GetCoursesApi,
  DeleteCoursesApi,
  AddCourseApi,
  UpdateCourseApi,
  GetCourseTypesApi,
  GetCourseLabelsApi,
  DownloadCourseTemplateApi
} from '@/api/course'
import * as XLSX from 'xlsx'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/CourseWrite.vue'
import Detail from './components/CourseDetail.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { useButtonPermiss } from '@/utils/buttonpermiss'
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()

import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()
const headers = ref({ Authorization: userStore.getToken ?? '' })
// console.log('uploadUrl', uploadUrl)
const { t } = useI18n()
interface Courser {
  courseName: string
  courseTypeName: string
  courseLabel: string
  courseLabels?: Array<string>
  createTime: string
}
let list: Courser[] = []
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await GetCoursesApi({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })
    list = res.data.pageModels || []
    list.map((item) => {
      item.courseLabels = item.courseLabel ? item.courseLabel.split(',') : []
    })
    //  if (row.courseLabels && row.courseLabel.includes(',')) {
    //     row.courseLabel = row.courseLabel.split(',')
    //   } else {
    //     row.courseLabel = row.courseLabel ? [row.courseLabel] : []
    //   }
    return {
      list: list,
      total: res.data.totalCount || 0
    }
  },
  fetchDelApi: async () => {
    const res = await DeleteCoursesApi(unref(ids))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const typeList = ref<selectionType[]>([])
const usersList = ref<selectionType[]>([])
const labelList = ref<selectionType[]>([])
const GetCourseTypes = async () => {
  const res = await GetCourseTypesApi({ pageFlag: false })
  res.data?.map((item) => {
    typeList.value.push({
      label: item.typeName,
      value: item.guid
    })
  })
  // const dt = await getUserListApi({ pageFlag: false })
  // let uList: selectionType[] = []
  // dt.data.pageModels?.map((item) => {
  //   uList.push({
  //     label: item.userNo + '  ' + item.userName,
  //     value: item.guid
  //   })
  // })
  // usersList.value = uList
  const labeldt = await GetCourseLabelsApi({ pageFlag: false })
  let lList: selectionType[] = []
  labeldt.data?.map((item) => {
    lList.push({
      label: item.labelName,
      value: item.labelName
    })
  })
  labelList.value = lList
}
onMounted(() => {
  console.log('onMounted')
  GetCourseTypes()
})

// GetCourseTypes()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },

  {
    field: 'courseName',
    label: '课程名称',
    sortable: true
  },

  {
    field: 'courseType',
    label: '课程类型',
    search: {
      component: 'Select',
      componentProps: {
        clearable: true,
        placeholder: '请选择课程类型'
      },
      optionApi: async () => {
        // let res = await GetCourseTypesApi({ pageFlag: false })
        // res.data?.map((item) => {
        //   typeList.value.push({
        //     label: item.typeName,
        //     value: item.guid
        //   })
        // })
        return typeList.value
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        filterable: true,
        clearable: true,
        placeholder: '请选择课程类型'
      },
      optionApi: async () => {
        // let res = await GetCourseTypesApi({ pageFlag: false })
        // res.data?.map((item) => {
        //   typeList.value.push({
        //     label: item.typeName,
        //     value: item.guid
        //   })
        // })
        return typeList.value
      }
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'courseTypeName',
    label: '课程类型',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    sortable: true
  },
  // {
  //   field: 'userGuid',
  //   label: '讲师',
  //   form: {
  //     component: 'Select',
  //     componentProps: {
  //       filterable: true,
  //       clearable: true,
  //       placeholder: '请选择讲师'
  //     },
  //     optionApi: async () => {
  //       return usersList.value
  //     }
  //   },
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       filterable: true,
  //       clearable: true,
  //       placeholder: '请选择讲师'
  //     },
  //     optionApi: async () => {
  //       return usersList.value
  //     }
  //   },
  //   table: {
  //     hidden: true
  //   }
  // },
  // {
  //   field: 'userName',
  //   label: '讲师',
  //   form: {
  //     hidden: true
  //   },
  //   search: {
  //     hidden: true
  //   },
  //   sortable: true
  // },
  {
    field: 'courseLabel',
    label: '课程标签',
    search: {
      component: 'Select',
      componentProps: {
        clearable: true,
        multiple: true,
        placeholder: '请选择课程标签'
      },
      optionApi: () => {
        return labelList.value
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'courseLabel',
    label: '课程标签',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'courseLabels',
    label: '课程标签',
    form: {
      component: 'Select',
      componentProps: {
        clearable: true,
        multiple: true,
        placeholder: '请选择课程标签'
      },
      optionApi: () => {
        return labelList.value
      }
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'courseContent',
    label: '课程内容',
    form: {
      component: 'Input',
      componentProps: {
        type: 'textarea',
        rows: 4,
        placeholder: '请输入课程内容'
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'remark',
    label: t('common.remark'),
    form: {
      component: 'Input',
      componentProps: {
        type: 'textarea',
        rows: 4,
        placeholder: '请输入备注'
      }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  // {
  //   field: 'userIntroduce',
  //   label: '讲师介绍',
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     component: 'Input',
  //     componentProps: {
  //       type: 'textarea',
  //       rows: 4,
  //       placeholder: '请输入讲师介绍'
  //     }
  //   }
  // },

  {
    field: 'createTime',
    label: t('userDemo.createTime'),
    width: 200,
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    sortable: true
  },
  // {
  //   field: 'courseStatus',
  //   label: t('menu.status'),
  //   width: '80px',
  //   slots: {
  //     default: (data: any) => {
  //       return (
  //         <>
  //           <ElTag size="small" type={data.row.courseStatus === 1 ? 'success' : 'danger'}>
  //             {data.row.courseStatus === 1 ? t('userDemo.over') : t('userDemo.naver')}
  //           </ElTag>
  //         </>
  //       )
  //     }
  //   },
  //   form: {
  //     hidden: true
  //   },
  //   detail: {
  //     slots: {
  //       default: (data) => {
  //         return <>{data.courseStatus === 1 ? t('userDemo.over') : t('userDemo.naver')}</>
  //       }
  //     }
  //   },
  //   search: {
  //     component: 'Select',
  //     value: [],
  //     componentProps: {
  //       placeholder: '请选择'
  //     },
  //     optionApi: async () => {
  //       return [
  //         { label: t('userDemo.enable'), value: 1 },
  //         { label: t('userDemo.disable'), value: 0 }
  //       ]
  //     }
  //   }
  // },
  {
    field: 'date',
    label: t('problem.time'),
    search: {
      component: 'DatePicker',
      componentProps: {
        style: { width: '240px' },
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        StartPlaceholder: 'Start date',
        EndPlaceholder: 'End date'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    align: 'center',
    fixed: 'right',
    width: 300,
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 240,
      slots: {
        default: (data: any) => {
          const row = data.row
          return (
            <>
              {haspermiss.value.includes('编辑') ? (
                <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
                  {t('exampleDemo.edit')}
                </BaseButton>
              ) : null}
              <BaseButton type="success" onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              {haspermiss.value.includes('删除') ? (
                <BaseButton type="danger" onClick={() => delData(data.row)}>
                  {t('exampleDemo.del')}
                </BaseButton>
              ) : null}
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  if (params.courseLabel.length > 0) {
    params.courseLabel = params.courseLabel.toString()
  } else {
    delete params.courseLabel
  }

  searchParams.value = params
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)
const ids = ref<string[]>([])

const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.guid] : elTableExpose?.getSelectionRows().map((v) => v.guid) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  // if (row.courseLabel && row.courseLabel.includes(',')) {
  //   row.courseLabel = row.courseLabel.split(',')
  //   console.log(' currentRow.courseLabel----', row.courseLabel)
  // } else {
  //   row.courseLabel = row.courseLabel ? [row.courseLabel] : []
  // }
  // if (type == 'edit') {
  //   console.log(' currentRow.courseLabel----', row.courseLabels)
  //   if (row.courseLabels && row.courseLabel.includes(',')) {
  //     row.courseLabel = row.courseLabel.split(',')
  //   } else {
  //     row.courseLabel = row.courseLabel ? [row.courseLabel] : []
  //   }
  // }
  currentRow.value = { ...row }
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

// const filterDep = (value: string, data: DepartmentItem) => {}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      console.log('formData---', formData)
      //  let p = filterDep(formData.depGuid, unref(departmentList))

      console.log('formData---', { formData })
      if (formData.courseLabels) {
        formData.courseLabel = formData.courseLabels.toString()
        delete formData.courseLabels
      }
      let res
      if (actionType.value == 'edit') {
        res = await UpdateCourseApi({ ...formData }).finally(() => {
          saveLoading.value = false
        })
      } else {
        formData.guid = ''
        res = await AddCourseApi({ ...formData }).finally(() => {
          saveLoading.value = false
        })
      }
      if (res) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}

const showExport = ref(false)
interface coursExport {
  课程名称: string
  课程类型: string
  课程标签: string
  创建时间: string
}
const handleData = () => {
  let arr: coursExport[] = []
  list.map((item) => {
    arr.push({
      课程名称: item.courseName,
      课程类型: item.courseTypeName,
      课程标签: item.courseLabel,
      创建时间: item.createTime
    })
  })
  return arr
}
const exportToExcel = () => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.json_to_sheet(handleData())

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, '课程列表.xlsx')
}
const successFile = (e) => {
  console.log('successFile-------', e)
  if (e.code == 0) {
    ElMessage.success('导入成功')
    showExport.value = false
    getList()
  } else {
    ElMessage.error(e.msg || '导入失败')
  }
}
const downExcel = async () => {
  const res = await DownloadCourseTemplateApi()
  if (res) {
    const excelFile = new Blob([res.data], {
      type: 'application/vnd.ms-excel'
    })

    // const url = URL.createObjectURL(excelFile)
    const url = window.URL.createObjectURL(excelFile)
    const a: HTMLAnchorElement = document.createElement('a')
    // 设置<a>元素的属性
    a.href = url
    a.download = '课程模板.xlsx'
    // 将<a>元素添加到文档中
    document.body.appendChild(a)
    // 触发点击事件
    a.click()
    URL.revokeObjectURL(a.href)
    // 移除<a>元素
    document.body.removeChild(a)
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction" v-if="haspermiss.includes('新增')">{{
        t('exampleDemo.add')
      }}</BaseButton>
      <BaseButton
        :loading="delLoading"
        type="danger"
        @click="delData(null)"
        v-if="haspermiss.includes('删除')"
      >
        {{ t('exampleDemo.del') }}
      </BaseButton>
      <BaseButton type="primary" @click="showExport = true" v-if="haspermiss.includes('导入')">{{
        t('exampleDemo.import')
      }}</BaseButton>
      <BaseButton type="primary" @click="exportToExcel" v-if="haspermiss.includes('导出')">{{
        t('exampleDemo.exprot')
      }}</BaseButton>
      <BaseButton type="primary" @click="downExcel">下载模板</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
  <Dialog v-model="showExport" title="导入模板">
    <div class="uploaddiv">
      <ElUpload
        accept=".xlsx, .xls"
        drag
        action="/api/Course/ExportCourses"
        :headers="headers"
        :on-success="successFile"
      >
        <el-icon class="el-icon--upload"><Plus /></el-icon>
        <div class="el-upload__text">点击或拖拽文件到此处上传</div>
        <div class="el-upload__text">支持.xlsx, .xls</div>
      </ElUpload>
    </div>
    <template #footer>
      <BaseButton @click="showExport = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
